package com.example.springbolgdemo.common.advice;

import com.example.springbolgdemo.pojo.response.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        //如果返回内容就是要统一返回类型直接返回
        if (body instanceof Result){
            return body;
        }
        //为String就先转换为返回类型再转换为json字符串类型返回
        if (body instanceof String){
            ObjectMapper mapper=new ObjectMapper();
            return mapper.writeValueAsString(Result.success(body));
        }

        //其他类型直接转换成Result类型
        return Result.success(body);
    }
}
